package com.yizisu.playerlibrary.impl

import android.content.Context
import android.media.AudioManager
import androidx.media.AudioAttributesCompat
import androidx.media.AudioFocusRequestCompat
import androidx.media.AudioManagerCompat

abstract class AudioFocusHelperCompat(
    context: Context,
    private val audioFocusListener: AudioManager.OnAudioFocusChangeListener
) {
    private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
    /*  private val audioFocusListener =
          AudioManager.OnAudioFocusChangeListener { focusChange ->
              when (focusChange) {
                  AudioManager.AUDIOFOCUS_GAIN -> {
                      if (shouldPlayWhenReady || player.playWhenReady) {
                          player.playWhenReady = true
                      }
                      shouldPlayWhenReady = false
                  }
                  AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK -> {
                      if (player.playWhenReady) {
                      }
                  }
                  AudioManager.AUDIOFOCUS_LOSS_TRANSIENT -> {
                      shouldPlayWhenReady = player.playWhenReady
                      player.playWhenReady = false
                  }
                  AudioManager.AUDIOFOCUS_LOSS -> {
                      abandonAudioFocus()
                  }
              }
          }*/

    /**
     * 获取音频焦点
     */
    private var audioFocusRequestCompat: AudioFocusRequestCompat? = null
    fun requestAudioFocus() {
        val result = AudioManagerCompat.requestAudioFocus(
            audioManager,
            buildFocusRequest().apply {
                audioFocusRequestCompat = this
            }
        )
        if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
            audioFocusListener.onAudioFocusChange(AudioManager.AUDIOFOCUS_GAIN)
        } else {
            audioFocusListener.onAudioFocusChange(AudioManager.AUDIOFOCUS_LOSS)
        }
    }

    /**
     * 停止音频焦点
     */
    fun abandonAudioFocus() {
        audioFocusRequestCompat?.let {
            AudioManagerCompat.abandonAudioFocusRequest(audioManager, it)
        }
    }

    /**
     * 构建请求
     */
    abstract fun buildFocusRequest(): AudioFocusRequestCompat

}